package com.lanchetech.user.aop;

import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.common.util.ThreadContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
public class HttpDtoAspect {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * com.lanchetech.user.controller..*(..)) ")
    public void webLog() {
    }

    @Before("webLog()")
    public void logRequest(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String uuid = ThreadContext.generateRequestUUID();
        MDC.put("reqid", uuid);
        log.info("requestid = {}, url={}, params={}, method_args={}", uuid, request.getRequestURL(), request.getQueryString(), Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(value = "webLog()", returning = "val")
    public void logResponse(Object val) {
        String uuid = ThreadContext.get(ThreadContext.REQ_UUID);
        if (val instanceof BaseResp) {
            ((BaseResp) val).setReqNo(uuid);
        } else if (val == null) {
            val = new Object();
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        List<String> filterUrl = Arrays.asList(
                "/api/category/findAllFrontCategoryList",
                "/api/home/getHomeInfo"
        );
        if (filterUrl.contains(request.getRequestURI())) {
            log.info("requestid = {} , url={}", uuid, request.getRequestURL());
        }else{
            log.info("requestid = {} , url={}, response={} ", uuid, request.getRequestURL(), val.toString());
        }
    }
}
